<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <uni-nav-bar title="健康知识" left-icon="back" @clickLeft="onBack" :border="false"></uni-nav-bar>
    <!-- 知识分类标签 -->
    <view class="category-tabs">
      <scroll-view scroll-x class="tabs-scroll">
        <view class="tabs-wrapper">
          <view v-for="(category, index) in categories" :key="index" class="tab-item"
            :class="{ active: activeCategory === index }" @click="switchCategory(index)">
            <text class="tab-text">{{ category.name }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 知识列表 -->
    <view class="knowledge-list">
      <view class="knowledge-item" v-for="(item, index) in filteredKnowledge" :key="item.id"
        @click="navigateToDetail(item.id)">
        <view class="item-image">
          <image :src="item.imageUrl" mode="widthFix"></image>
        </view>
        <view class="item-content">
          <text class="item-title">{{ item.title }}</text>
          <text class="item-desc">{{ item.description }}</text>
          <view class="item-info">
            <text class="item-category">{{ item.categoryName }}</text>
            <text class="item-date">{{ item.publishDate }}</text>
          </view>
        </view>
      </view>
      <!-- 空状态 -->
      <view class="empty-state" v-if="filteredKnowledge.length === 0">
        <uni-icons type="book" size="60" color="#ccc"></uni-icons>
        <text class="empty-text">未找到相关健康知识</text>
        <button class="reset-button" @click="resetFilter" v-if="searchKeyword || activeCategory !== 0">
          重置筛选条件
        </button>
      </view>
      <!-- 加载更多 -->
      <view class="load-more" v-if="filteredKnowledge.length > 0 && hasMore">
        <uni-load-more :status="loadingStatus" @clickLoadMore="loadMore"></uni-load-more>
      </view>
    </view>
  </view>
</template>

<script>
import api from '@/api/index';
export default {
  data() {
    return {
      // 分类数据
      categories: [
        { id: 'all', name: '全部' },
        { id: 'disease', name: '疾病知识' },
        { id: 'medication', name: '用药指南' },
        { id: 'nutrition', name: '营养饮食' },
        { id: 'fitness', name: '运动健康' },
        { id: 'mental', name: '心理健康' },
        { id: 'elderly', name: '老年健康' }
      ],
      // 当前选中的分类索引
      activeCategory: 0,
      // 健康知识数据
      knowledgeData: [],
      // 加载状态
      loadingStatus: 'more',
      // 是否有更多数据
      hasMore: true,
      currentPage: 1,
      pageSize: 10,
      isLoading: false
    };
  },
computed: {
  // 根据分类和搜索关键词筛选知识
  filteredKnowledge() {
    // 添加防御性检查，确保knowledgeData是数组
    let result = Array.isArray(this.knowledgeData) ? [...this.knowledgeData] : [];
    // 按分类筛选
    if (this.activeCategory !== 0 && result.length > 0) {
      // 使用分类名称进行筛选
      const categoryName = this.categories[this.activeCategory]?.name || '';
      result = result.filter(item => item.categoryName === categoryName);
    }
    return result;
  }
},
  methods: {
    // 返回上一页
    onBack() {
      uni.navigateBack();
    },
    // 重置筛选条件
    resetFilter() {
      this.activeCategory = 0;
    },
    // 跳转到详情页
    navigateToDetail(id) {
      uni.navigateTo({
        url: `/components/knowledgeDetail?id=${id}`
      });
    },
    // 加载更多
    async loadMore() {
      if (this.isLoading || !this.hasMore) return;
      this.isLoading = true;
      this.loadingStatus = 'loading';
      try {
        const res = await api.getHealthArticlesApi(this.currentPage + 1, this.pageSize);

        if (res.data.length === 0) {
          this.hasMore = false;
          this.loadingStatus = 'noMore';
          return;
        }
        this.knowledgeData = [...this.knowledgeData, ...res.data];
        this.currentPage++;
        this.loadingStatus = 'more';
      } finally {
        this.isLoading = false;
      }
    },
    // 获取健康知识数据
    async gethealtharticlesapi() {
      this.knowledgeData = [];
      this.currentPage = 1;
      this.hasMore = true;
      this.loadingStatus = 'loading';
      try {
        const res = await api.getHealthArticlesApi(1, this.pageSize);
        console.log(res);
        
        this.knowledgeData = res.data;
        console.log(this.knowledgeData);
        
        this.loadingStatus = res.data.length < this.pageSize ? 'noMore' : 'more';
      } catch (error) {
        this.loadingStatus = 'more';
      }
    },
    // 切换分类
    switchCategory(index) {
      this.activeCategory = index;
      this.gethealtharticlesapi();
      uni.pageScrollTo({ scrollTop: 0, duration: 300 });
    },
    onPullDownRefresh() {
      this.gethealtharticlesapi().then(() => uni.stopPullDownRefresh());
    },
    onReachBottom() {
      this.loadMore();
    },
    onLoad() {
      this.gethealtharticlesapi();
    },
  }
}

</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 搜索框样式 */
.search-box {
  padding: 15rpx 20rpx;
  background-color: #f5f5f5;
}

/* 分类标签样式 */
.category-tabs {
  background-color: #fff;
  padding: 10rpx 0;
  border-bottom: 1px solid #eee;
}

.tabs-scroll {
  white-space: nowrap;
  padding: 0 20rpx;
}

.tabs-wrapper {
  display: inline-flex;
  gap: 30rpx;
}

.tab-item {
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  margin: 5rpx 0;
}

.tab-text {
  font-size: 28rpx;
  color: #666;
}

.tab-item.active {
  background-color: #e8f4fd;
}

.tab-item.active .tab-text {
  color: #007aff;
  font-weight: 500;
}

/* 知识列表样式 */
.knowledge-list {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.knowledge-item {
  display: flex;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
  &:hover {
    transform: translateY(-2rpx);
  }
}

.item-image {
  width: 200rpx;
  height: 140rpx;
  flex-shrink: 0;
  image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.item-content {
  flex: 1;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 10rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  line-height: 1.4;
}

.item-desc {
  font-size: 24rpx;
  color: #666;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
  margin-bottom: 10rpx;
  line-height: 1.3;
}

.item-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-category {
  font-size: 22rpx;
  color: #007aff;
  background-color: #e8f4fd;
  padding: 3rpx 12rpx;
  border-radius: 12rpx;
}

.item-date {
  font-size: 22rpx;
  color: #999;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 150rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #888;
  margin: 30rpx 0;
}

.reset-button {
  background-color: #f5f5f5;
  color: #007aff;
  border: 1rpx solid #007aff;
  border-radius: 50rpx;
  padding: 15rpx 40rpx;
  font-size: 26rpx;
  margin-top: 20rpx;
}

/* 加载更多样式 */
.load-more {
  padding: 30rpx 0;
  display: flex;
  justify-content: center;
}
</style>
